//
//  UITextView+Emoticon.swift
//  emotionKeyBoard
//
//  Created by 路峻鉴 on 15/10/17.
//  Copyright © 2015年 路峻鉴. All rights reserved.
//

import UIKit

extension UITextView {
    
    ///插入表情符号
    func insertEmotion(emotion: Emotion) {
        //emoji表情
        if emotion.emoji != nil {
            replaceRange(selectedTextRange!, withText: emotion.emoji!)
            return
        }
        //图片表情
        if emotion.chs != nil {
            //获取图片字符串
            let attachment = EmotionAttachment()
            attachment.chs = emotion.chs
            attachment.image = UIImage(contentsOfFile: emotion.imagePath)
            //设置表情图片大小
            let heiget = font!.lineHeight
            attachment.bounds = CGRect(x: 0, y: -4, width: heiget, height: heiget)
            let imgaeText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            //设置文本属性
            imgaeText.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, 1))
            
            //插入到文本
            //-获取可变的文本属性
            let attrString = NSMutableAttributedString(attributedString: attributedText)
            //-插入文本
            attrString.replaceCharactersInRange(selectedRange, withAttributedString: imgaeText)
            //-赋值textView
            //--获取光标
            let range = selectedRange
            attributedText = attrString
            //--恢复光标
            selectedRange = NSRange(location: range.location + 1, length: 0)
        }
    }
    ///计算型属性，返回完整字符串
    var emoticonText: String {
        //获取text原本文本
        let textStr = attributedText
        var stringM = String()
        
        textStr.enumerateAttributesInRange(NSMakeRange(0, textStr.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dic, range, _) -> Void in
            if let attachment = dic["NSAttachment"] as? EmotionAttachment {
                stringM += attachment.chs!
            } else {
                let string = (textStr.string as NSString).substringWithRange(range)
                stringM += string
            }
        }
        
        return stringM
    }
}